﻿using Core.SimpleTemp.Common;
using Microsoft.Extensions.Options;
using System;

/*----------------------------------------------------------------
* 描述 ：对临时目录操作帮助类
* 作    者 ：Tengsheng Hou
* 更新时间 ：2019/7/29 9:38:40
//----------------------------------------------------------------*/
namespace Core.Toolkit.Common
{
    public class TempDirHelp
    {

        public TempDirModel TempDirModel { get; }

        /// <summary>
        /// 生成一个已时间戳命名的文件名
        /// </summary>
        /// <param name="FiletExtension">文件后缀 例：(.txt)</param>
        public static string GetTimeStampFielName(string filetExtension)
        {
            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            var timeStamp = Convert.ToInt64(ts.TotalSeconds).ToString();
            return timeStamp + filetExtension;
        }


        /// <summary>
        /// 在系统临时路径中，生成一个已时间戳命名的文件路径
        /// </summary>
        /// <param name="FiletExtension">文件后缀 例：(.txt)</param>
        /// <returns></returns>
        public string GetFilePath(string filetExtension)
        {
            var fileNmae = GetTimeStampFielName(filetExtension);
            return System.IO.Path.Combine(TempDirModel.TempDir, fileNmae);
        }


        #region 
        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="tempDirModel"></param>
        public TempDirHelp(TempDirModel tempDirModel)
        {
            TempDirModel = tempDirModel;
        }
        #endregion

        /// <summary>
        /// 
        /// </summary>
        public void Clear()
        {
            var fileList = System.IO.Directory.GetFiles(TempDirModel.TempDir);
            var nowTime = DateTime.Now;
            foreach (var file in fileList)
            {
                var lastWriteTime = System.IO.File.GetLastWriteTime(file);
                var timeDiff = nowTime - lastWriteTime;
                var timeDiffMinute = timeDiff.TotalMinutes;
                if (timeDiffMinute > TempDirModel.ClearFileDiffTiem)
                    try { System.IO.File.Delete(file); } catch (Exception) { }
            }
        }

    }


    /// <summary>
    /// 对临时目录操作帮助类
    /// </summary>
    [AutoDi(null, AutoDiAttribute.Singleton)]
    public class TempDirDiHelp : TempDirHelp
    {
        public TempDirDiHelp(IOptionsMonitor<WebAppOptions> webAppOptions) : base(webAppOptions.CurrentValue.TempDirModel)
        {

            if (!System.IO.Directory.Exists(TempDirModel.TempDir))
            {
                System.IO.Directory.CreateDirectory(TempDirModel.TempDir);
            }
        }
    }

    public class TempDirModel
    {
        /// <summary>
        /// 临时文件目录
        /// </summary>
        public string TempDir { get; set; }
        /// <summary>
        /// 文件创建后多久清理掉（单位：分钟）
        /// </summary>
        public int ClearFileDiffTiem { get; set; }

    }
}
